#include "../tcpServer.hpp"

class EchoServer
{
private:
    TcpServer _server;

    void OnConnect(const ConnectionPtr &connection)
    {
        LOG(DEG, "establish a new connection, id: %d", connection->getConnectionId());
    }

    void OnClose(const ConnectionPtr &connection)
    {
        LOG(DEG, "connection closed, id: %d", connection->getConnectionId());
    }

    void OnMessage(const ConnectionPtr &connection) // 业务处理回调 处理输入缓冲区中的数据
    {
        Buffer *buf = connection->getInBuffer();
        std::string message;
        buf->ReadAsString(message, buf->getAbleReadSize());
        LOG(DEG, "client say: %s", message.c_str());
        message += "\n";
        //std::string response = "hello client, I'm server\n";
        connection->send(message.c_str(), message.size()); // 先将数据写入发送缓冲区中 再开启写事件监控 写事件触发时 将处理结果发送给客户端
        connection->checkOutBuffer();//回显一次就设置连接为待关闭状态 写事件触发调用handleWrite后直接关闭连接
    }

    void OnEvents(const ConnectionPtr &connection)
    {
        LOG(DEG, "OnEvents execute");
    }

public:
    EchoServer(uint16_t port)
    : _server(port)
    {
        _server.setThreadCount(2);
        _server.enableInactiveRelease(10);
        _server.setConnectedCallback(std::bind(&EchoServer::OnConnect, this, std::placeholders::_1));
        _server.setClosedCallback(std::bind(&EchoServer::OnClose, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1));
    }

    void start() { _server.start(); }
};